import React,{useState,useEffect,useRef} from 'react'
import { PageHeader,Steps,Button ,message,Form,Input,Select,notification  } from 'antd'
import style from './News.module.css'
import './News.module.css'
import axios from 'axios';
import NewsEditor from '../../../components/news-manage/NewsEditor';
const { Step } = Steps;
const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
export default function NewsUpdate(props) {
  const [current, setcurrent] = useState(0)
  const [categoryList, setcategoryList] = useState([])
  const NewsForm = useRef(null)
  const [formInfo, setformInfo] = useState({})
  const [content, setcontent] = useState('')
  useEffect(() => {
    axios.get(`/categories`).then(res=>{
      setcategoryList(res.data)
    })
    return () => {
      
    }
  }, [])
  useEffect(() => {
    axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res=>{
        const {title,categoryId,content} = res.data
        NewsForm.current.setFieldsValue({
            title,
            categoryId
        })
        setcontent(content)
    })
    return () => {
      
    }
  }, [props.match.params.id])
  
  const next = () => {
    // 进行表单校验
    if(current === 0) {
      NewsForm.current.validateFields().then(res=>{
        setformInfo(res)
        setcurrent(current + 1);
      }).catch(err=>{
        console.log(err)
      })
    }else{
      if(content === '' || content.trim() === '<p></p>'){
        message.error('新闻内部不能为空')
      }else{
        setcurrent(current + 1);
      }
    }
  };

  const prev = () => {
    setcurrent(current - 1);
  };
  const steps = [
    {
      title: '基本信息',
      description: '新闻标题，新闻分类',
    },
    {
      title: '新闻内容',
      description: '新闻主题内容',
    },
    {
      title: '新闻提交',
      description: '保存草稿或提交审核',
    },
  ];
 
  // const User = JSON.parse(localStorage.getItem('token'))
  const handleSave = (auditState)=>{
    axios.patch(`/news/${props.match.params.id}`,{
      ...formInfo,
      "content":content,
      "auditState": auditState,
      "createTime": Date.now(),
    }).then(res=>{
      props.history.push(auditState===0?`/news-manage/draft`:`/audit-manage/list`)
      notification.info({
        message: `通知`,
        description:
          `您可以到${auditState===0 ?'草稿箱' : '审核列表'}中查看您的新闻`,
        placement:'bottomRight'
      });
    })
  }
  return (
    <div>
       <PageHeader
          className="site-page-header"
          title="新闻更新"
          subTitle="This is a subtitle"
          onBack={()=>{props.history.goBack()}}
        />
        <Steps current={current}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} description = {item.description}/>
          ))}
        </Steps>
        <div className={style.newsContent}>
          <div className={current === 0 ? '' :style.active}>
            <Form {...layout} name="control-hooks" ref={NewsForm}>
              <Form.Item name="title" label="新闻标题" rules={[{ required: true,message: '请输入新闻标题!' }]}>
                <Input />
              </Form.Item>
              <Form.Item name="categoryId" label="新闻分类" rules={[{ required: true,message: '请选择一项分类!' }]}>
                <Select
                  allowClear
                >
                  {
                    categoryList.map(item=>
                      <Option value={item.id} key={item.id}>{item.title}</Option>
                    )
                  }
                </Select>
              </Form.Item>
            </Form>
          </div>
          <div className={current === 1 ? '' :style.active}>
            <NewsEditor getContent={(value)=>{setcontent(value)}} content={content}></NewsEditor>
          </div>
        </div>
        
        <div className="steps-action">
          {current < steps.length - 1 && (
            <Button type="primary" onClick={() => next()}>下一步</Button>
          )}
          {current === steps.length - 1 && (
            <span>
              <Button type="primary" onClick={() =>handleSave(0)}>保存草稿箱</Button>
              <Button type="primary" onClick={() =>handleSave(1)} style={{margin: '0px 0px 0px 8px'}} danger>提交审核</Button>
            </span>
            
          )}
          {current > 0 && (
            <Button style={{ margin: '0 8px' }} onClick={() => prev()}>上一步</Button>
          )}
        </div>
    </div>
  )
}
